# coding: utf-8

from sqlalchemy import event
from sqlalchemy.orm.attributes import flag_modified

from app.products.constant import TypeToName
from .models import ProductTemplate, ProductToParam, TechnologyParams, Brand


@event.listens_for(ProductTemplate.spec_settings, 'set')
def mark_spec_settings_changed(target, value, oldvalue, initiator):
    """
    create by ld_wu 2018-01-09
    修改产品模板规格，需要标识字段修改方可更新成功
    """
    # NOTE SQLAlchemy JSON 列表中包含字段修改保存不生效
    # 需要显式调用声明该字段已被修改方可生效
    flag_modified(target, 'spec_settings')


@event.listens_for(ProductToParam, 'after_update')
def update_sync_template_name(mapper, connection, target):
    """
    create by ld_wu 2018-01-20
    产品技术参数更新后同步更新产品名称
    """
    if target.is_display:
        template = ProductTemplate.get_by_id(target.product_template_id)
        if template:
            name = get_product_name(template)
            connection.execute(
                ProductTemplate.__table__.update().values(
                    name=name,
                ).where(
                    ProductTemplate.__table__.c.id == target.product_template_id
                )
            )


@event.listens_for(ProductToParam.technology_param_id, 'set')
def sync_info_from_template(target, value, oldvalue, initiator):
    """
    create by ld_wu 2018-01-09
    """
    if value:
        template = TechnologyParams.get_by_id(value)
        if template:
            target.is_display = template.is_display
            target.name = template.name
            target.calculate_item = template.calculate_item
            target.unit = template.is_display
            target.weight = template.weight
            target.is_required = template.is_required
            target.display_rule = template.display_rule
            target.options = template.options
            target.parent_id = template.parent_id
            target.tag_type = template.tag_type
            target.placeholder = template.placeholder


@event.listens_for(ProductToParam, 'after_insert')
def insert_sync_template_name(mapper, connection, target):
    """
    create by ld_wu 2018-01-20
    创建产品技术参数时同步更新产品名称
    """
    if target.is_display:
        template = ProductTemplate.get_by_id(target.product_template_id)
        if template:
            name = get_product_name(template)
            connection.execute(
                ProductTemplate.__table__.update().values(
                    name=name,
                ).where(
                    ProductTemplate.__table__.c.id == target.product_template_id
                )
            )


@event.listens_for(Brand.brand_name, 'set',  active_history=True)
def sync_template_name_from_brand(target, value, oldvalue, initiator):
    """
    create by ld_wu 2018-01-09
    修改品牌名称时，更新产品模板名称
    """
    if value != oldvalue:
        templates = ProductTemplate.get_list_by_args(brand_id=target.id)
        for each in templates:
            each.name = get_product_name(each, value)


@event.listens_for(ProductTemplate.brand_id, 'set',  active_history=True)
def sync_template_name_from_brand_id(target, value, oldvalue, initiator):
    """
    create by ld_wu 2018-01-09
    修改品牌名称时，更新产品模板名称
    """
    if value != oldvalue:
        brand = Brand.get_by_id(value)
        if brand:
            target.name = get_product_name(target, brand.brand_name)


def get_product_name(template, brand_name=''):
    return '{}·{} {}'.format(
        brand_name or template.brand,
        TypeToName.mapping.get(template.product_type_id, ''),
        template.title_display
    )